<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">

          <el-form-item label="员工姓名" prop="coachName">
            <el-input v-model="queryParams.coachName" placeholder="请输入员工姓名" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="CameraFilled" type="primary" @click="ClickCamera">相机拍照</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['primary:coach:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['primary:coach:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['primary:coach:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['primary:coach:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="coachList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column label="员工姓名" align="center" prop="coachName" />

        <el-table-column label="手机号" align="center" prop="phone" />
        <el-table-column label="性别" align="center">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
          </template>
        </el-table-column>
        <el-table-column label="下发详情" align="center">
          <template #default="scope">
            <div v-for="item in scope.row.coachSyncList">
              <span> 相机名称:{{ item.deviceName }}-
                {{item.syncStatus == 0 ? '未同步' : item.syncStatus == 1 ? '已同步' :
              item.syncStatus == 2 ? '同步中' : item.syncStatus == 3 ? '删除中' : '未知状态' }};
              </span>
              <span v-if="item.failReason !== null"> 失败原因:{{ item.failReason }} </span>
            </div>
          </template>
        </el-table-column>

        <!--        <el-table-column label="人员类型" align="center">
          <template #default="scope">
            <dict-tag :options="g_peoplelist_type" :value="scope.row.coachType" />
          </template>
        </el-table-column> -->

        <!--        <el-table-column label="有无团课" align="center" prop="whetherLeagueClass">
          <template v-slot="{ row }">
            {{ row.whetherLeagueClass == 0 ? '有' : '无' }}
          </template>
        </el-table-column> -->
        <el-table-column label="简介" align="center" prop="briefIntroduction" />
        <!-- <el-table-column label="标签" align="center" prop="label" /> -->
        <!-- <el-table-column label="对象存储主键" align="center" prop="ossId" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['primary:coach:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['primary:coach:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="重新下发" placement="top">
              <el-button link type="primary" icon="Refresh" @click="handleUpdateResh(scope.row)"
                v-hasPermi="['primary:coach:edit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改教练信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="coachFormRef" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="图片" prop="ossId">
          <imageUpload v-model="form.ossId" ref="childValue" :limit='1' />
        </el-form-item>

        <el-form-item label="员工姓名" prop="coachName">
          <el-input v-model="form.coachName" placeholder="请输入员工姓名" @input="trimInput('coachName')" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">

          <el-select v-model="form.sex" placeholder="请选择">
            <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="人员类型" prop="coachType">

          <el-select v-model="form.coachType" placeholder="请选择">
            <el-option v-for="dict in g_peoplelist_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="角色" prop="roleIds" v-if="dialog.xiugai">
          <el-select v-model="form.roleIds" multiple placeholder="请选择">
            <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId"
              :disabled="item.status == '1'"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="归属部门" prop="deptId" v-if="dialog.xiugai">
          <el-tree-select v-model="form.deptId" :data="deptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属部门"
            check-strictly />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" type="text" maxlength="11" @input="trimInput('phone')" />
        </el-form-item>
        <el-form-item label="账号" prop="userName" v-if="dialog.xiugai">
          <el-input v-model="form.userName" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialog.xiugai">
          <el-input v-model="form.password" placeholder="请输入密码" show-password />
        </el-form-item>

        <el-form-item label="简介" prop="briefIntroduction">
          <el-input v-model="form.briefIntroduction" placeholder="请输入简介" @input="trimInput('briefIntroduction')" />
        </el-form-item>


      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="dialogResh.title" v-model="dialogResh.visible" width="1200px" append-to-body>
      <el-form ref="memberFormRef" :model="FormResh" label-width="100px">
        <!--        <el-form-item label="图片" prop="ossId">
              <imageUpload v-model="form.ossId" ref="childValue" :limit="1" :fileSize="1" :rule="1" />
            </el-form-item> -->
        <el-form-item label="设备选择" prop="deviceId">
          <el-select v-model="FormResh.deviceId" placeholder="请选择" filterable multiple>
            <el-option v-for="dict in deviceList" :key="dict.id" :label="dict.deviceName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitFormResh">确 定</el-button>
          <el-button @click="cancelResh">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="dialogCamera.title" v-model="dialogCamera.visible" width="1200px" append-to-body>
      <div id="app">
        <Camera />
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Coach" lang="ts">
  import api from "@/api/system/user"
  import { nextTick } from 'vue';
  import { listCoach, getCoach, delCoach, addCoach, updateCoach } from '@/api/primary/coach';
  import { updateRePush } from '@/api/primary/member';
  import { listDevice } from '@/api/primary/device';
  import { CoachVO, CoachQuery, CoachForm } from '@/api/primary/coach/types';
  import { DeptVO } from "@/api/system/dept/types";
  import { defineComponent } from 'vue';
  import Camera from '@/components/Camera';
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { sys_user_sex, g_peoplelist_type } = toRefs<any>(proxy?.useDict("sys_user_sex", "g_peoplelist_type"));
  const deptOptions = ref<DeptVO[]>([]);
  const coachList = ref<CoachVO[]>([]);
  const buttonLoading = ref(false);
  const deviceList = ref<any>([]);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const roleOptions = ref<RoleVO[]>([]);
  const queryFormRef = ref<ElFormInstance>();
  const coachFormRef = ref<ElFormInstance>();
  const idsname = ref<Array<string | number>>([]);
  const dialog = reactive<DialogOption>({
    visible: false,
    title: '',
    xiugai: true
  });
  const gymIdValue = ref();
  const FormResh = ref<any>({
    id: undefined,
    deviceId: undefined//
  });
  const dialogCamera = reactive<DialogOption>({
    visible: false,
    title: '相机拍照'
  });
  const initFormData : CoachForm = {
    id: undefined,
    gymId: undefined,
    coachName: undefined,
    gymUserId: undefined,
    phone: undefined,
    sex: undefined,
    coachType: undefined,
    whetherLeagueClass: undefined,
    briefIntroduction: undefined,
    password: undefined,
    label: undefined,
    ossId: undefined,
    deptId: undefined,
    roleIds: []
  }
  const data = reactive<PageData<CoachForm, CoachQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      password: undefined,
      gymId: undefined,
      coachName: undefined,
      gymUserId: undefined,
      deptId: undefined,
      phone: undefined,
      sex: undefined,
      coachType: undefined,
      whetherLeagueClass: undefined,
      briefIntroduction: undefined,
      label: undefined,
      ossId: undefined,
      params: {
      }
    },
    rules: {
      password: [
        { required: true, message: "密码不能为空", trigger: "blur" }
      ],
      roleIds: [{ required: true, message: "请选择角色", trigger: "blur" }],
      userName: [
        { required: true, message: "账号不能为空", trigger: "blur" }
      ],
      coachName: [
        { required: true, message: "员工姓名不能为空", trigger: "blur" }
      ],
      gymUserId: [
        { required: true, message: "人员id不能为空", trigger: "blur" }
      ],
      phone: [
        { required: true, message: "手机号不能为空", trigger: "blur" }
      ],
      sex: [
        { required: true, message: "性别不能为空", trigger: "change" }
      ],
      coachType: [
        { required: true, message: "人员类型不能为空", trigger: "change" }
      ],
      whetherLeagueClass: [
        { required: true, message: "有无团课；0有 1无不能为空", trigger: "blur" }
      ],
      briefIntroduction: [
        { required: false, message: "简介不能为空", trigger: "blur" }
      ],
      label: [
        { required: true, message: "标签不能为空", trigger: "blur" }
      ],
      ossId: [
        { required: true, message: "图片不能为空", trigger: "blur" }
      ],
      deptId: [
        { required: true, message: "归属部门不能为空", trigger: "blur" }
      ],
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询教练信息列表 */
  const getList = async () => {
    loading.value = true;
    const res = await listCoach(queryParams.value);
    coachList.value = res.rows;
    console.log(coachList.value, 'coachList.valuecoachList.value')
    total.value = res.total;
    if(total.value>0){
      gymIdValue.value=res.rows[0].gymId
    }
    loading.value = false;
  }

  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }

  /** 修改按钮操作 */
  const handleUpdateResh = async (row ?: CoachVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getCoach(_id);
    Object.assign(form.value, res.data);
    dialogResh.visible = true;
    dialogResh.title = "重新下发";
  }
  const trimInput = (field) => {
    nextTick(() => {
      if (form.value[field]) {
        form.value[field] = form.value[field].trim();
      }
    });
  };
  /** 取消按钮 */
  const cancelResh = () => {
    reset();
    dialogResh.visible = false
  }
  /** 重新下发 */
  const submitFormResh = async () => {
    if (FormResh.value.deviceId.length == 0) {
      proxy?.$modal.msgError("请先选择设备!");
      return
    }
    FormResh.value.coachId = form.value.id
    FormResh.value.gymId=gymIdValue.value
    buttonLoading.value = true;
    await updateRePush(FormResh.value).finally(() => buttonLoading.value = false);
    proxy?.$modal.msgSuccess("提交成功");
    dialogResh.visible = false;
    await getList();
  }
  const dialogResh = reactive<DialogOption>({
    visible: false,
    title: ''
  });
  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    coachFormRef.value?.resetFields();
  }
  /** 查询设备列表 */
  const getListDevice = async () => {
    loading.value = true;
    const res = await listDevice(queryParams.value);
    deviceList.value = res.rows;
  }
  const ClickCamera = () => {
    dialogCamera.visible = true
  }
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }
  /** 查询部门下拉树结构 */
  const getTreeSelect = async () => {
    const res = await api.deptTreeSelect();
    deptOptions.value = res.data;
  };
  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : CoachVO[]) => {
    ids.value = selection.map(item => item.id);
    idsname.value = selection.map(item => item.coachName);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }


  /** 新增按钮操作 */
  const handleAdd = async () => {
    reset();
    const { data } = await api.getUser();
    dialog.visible = true;
    dialog.xiugai = true;
    dialog.title = "添加人员信息";
    roleOptions.value = data.roles;
  }
  /** 修改按钮操作 */
  const handleUpdate = async (row ?: CoachVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getCoach(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.xiugai = false;
    dialog.title = "修改人员信息";
  }

  /** 提交按钮 */
  const submitForm = () => {
    coachFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateCoach(form.value).finally(() => buttonLoading.value = false);
        } else {
          await addCoach(form.value).finally(() => buttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("新增成功");
        dialog.visible = false;
        await getList();
      }
    });
  }

  /** 删除按钮操作 */
  const handleDelete = async (row ?: CoachVO) => {
    const _ids = row?.id || ids.value;
    const name = row?.coachName || idsname.value;
    await proxy?.$modal.confirm('是否确认删除教练信息编号为"' + name + '"的数据项？').finally(() => loading.value = false);
    await delCoach(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('primary/coach/export', {
      ...queryParams.value
    }, `coach_${new Date().getTime()}.xlsx`)
  }

  onMounted(() => {
    getTreeSelect() // 初始化部门数据
    getListDevice()
    getList();
  });
</script>
